/**
 * 包含常用的方法
 *
 * @author 小陆
 */
var sy = $.extend({}, sy); /* 全局对象 */

var custom = $.extend({}, custom); /* 全局对象 */
//标记,主要用于是否提交,是否修改
sy.mark = false;
//标志位,禁止频繁查询提交,页面数据是否更改
sy.sign = false;


/**
 * 表格状态修改
 */
custom.statusEdit = function (element, status) {
    var id = $(element).attr('data-id'),
        url = $(element).attr('data-url') + "id=" + id,
        display = $(element).attr('data-display') == 1 ? 0 : 1,
        data = {};

    data = {
        display: display
    };
    // function (url, data, success, async, error)
    if (status) {
        sy.post(
            url,
            { data: data },
            function (data, textStatus, xhr) {
                sy.tip(data.message, data.success);

                var removeClass = display == 1 ? 'icon-disable' : 'icon-enable';
                var addClass = display == 0 ? 'icon-disable' : 'icon-enable';

                $(element).attr('data-display', display)
                    .removeClass(removeClass)
                    .addClass(addClass);
            },
            true);
    }
}


/**
 * 多线程执行行数,延迟执行函数
 */
sy.thread = function (fun, time) {
    if (typeof time === 'undefined' || typeof time !== 'number') {
        time = 50;
    }
    if (typeof fun !== 'function') {
        return;
    }
    window.setTimeout(function () {
        fun();
    }, time);
};
/**
 * 增加formatString功能
 * 使用方法：sy.fs('字符串{0}字符串{1}字符串','第一个变量','第二个变量');
 */
sy.fs = function (str) {
    for (var i = 0; i < arguments.length - 1; i++) {
        str = str.replace('{' + i + '}', arguments[i + 1]);
    }
    return str;
};
/**
 * 封装url
 */
sy.url = function (opts, param = '') {
    if (_A_ === undefined) return '';
    if (typeof opts == 'string') {
        opts = {
            a: opts
        };
    }
    var options = $.extend({
        a: _A_,
        c: _C_,
        m: _M_
    },
        opts
    );

    param = $.extend({}, opts && opts.param ? opts.param : {}, param || {});

    var url = sy.fs('/{0}/{1}/{2}', options.m, options.c, options.a);

    if (param != '' || param.length != 0) {
        url += (/\?/.test(url) ? '&' : '?') + $.param(param);
    }

    return url;
};
sy.mask = function (elem = window.top.document.body) {
    $(elem).append("<div id=mask class=\"overlay\"><i class=\"fas fa-2x fa-sync fa-spin\"></i></div>")
    setTimeout(function () {
        sy.unmask();
    }, 5000);
}
sy.unmask = function () {
    $(window.top.document.body).find("#mask").remove();
    // $(window.top.document.body)("<div class=\"overlay\"><i class=\"fas fa-2x fa-sync fa-spin\"></i></div>")
}

$(document).ready(sy.unmask);
/**
 * 缩写全拼:preventMoreSubmit
 * 防止用户拼命回车,阻塞通道
 */
sy.pms = function (time) {
    sy.sign = true;

    if (typeof time === 'undefined' || typeof time !== 'number') {
        time = 300;
    }

    sy.thread(function () {
        sy.sign = false;
    }, time);
};

/**
 * open
 * @param url 打开的url地址
 * @param opts 配置
 */

sy.open = function (url, opts) {
    return $.open(url, opts);
};

/**
 * 警告
 * @author kaiyuan
 * @requires artDialog
 * @param content 内容
 */

var Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000
});
sy.tip = function (message, success) {

    parent.Toast.fire({
        icon: success,//success,info,error,warning,question
        title: message
    })
};



/**
 * 后台响应处理
 * @param  object XMLHTTPRequest
 * @param  json data
 */
sy.responseHandle = function (XMLHTTPRequest, data) {
    var status = parseInt(XMLHTTPRequest.status);

    switch (status) {
        case 501: // debug信息
        case 500: // 服务器内部错误 异常/错误
        case 417: // 数据库错误
            //success,info,error,warning,question
            sy.tip(XMLHTTPRequest.responseText, "error");
            break;
        case 403: // 权限不足
            sy.tip(sy.readXhrData(XMLHTTPRequest).message, "warning");
            break;
        case 400: // 错误请求, 验证失败
            sy.tip(sy.readXhrData(XMLHTTPRequest).message, "error");
            break;
        case 200: // 成功请求

            data = typeof (data) == 'object' ? data : $.parseJSON(data);

            sy.tip(data.message, "error");

            break;
    }

    return;
};

/**
 * 读取xhr里面的json数据
 * @param  object XMLHTTPRequest
 * @return {[type]}                [description]
 */
sy.readXhrData = function (XMLHTTPRequest) {
    // dataType为json的时候
    var jsonData = XMLHTTPRequest.responseJSON;
    try {
        if (!jsonData) {
            if (XMLHTTPRequest.responseText) {
                // dataType为html的时候
                jsonData = $.parseJSON(XMLHTTPRequest.responseText);
            } else if (XMLHTTPRequest.response) {
                // dataType为上传文件时
                jsonData = $.parseJSON(XMLHTTPRequest.response);
            }
        }
    } catch (e) {
        jsonData = {};
    }

    return jsonData;
};




$.each(['get', 'post'], function (i, method) {
    sy[method] = function (url, data, success, async, error) {
        // shift arguments if data argument was omitted
        async = async == undefined || async == true || false;

        if ($.isFunction(data)) {
            async = success == undefined || success == true || false;
            success = data;
            data = undefined;
        }
        if (typeof success === 'boolean') {
            async = success;
            success = false;
        }
        if (typeof data === 'boolean') {
            async = data;
            data = undefined;
            success = false;
        }
        return $.ajax({
            url: url,
            cache: true,
            type: method,
            dataType: 'json',
            data: data,
            async: async,
            success: function (data, textStatus, xhr) {
                success && success.call(this, data, textStatus, xhr);
            },
            beforeSend: function (xhr, settings) {

                xhr.setRequestHeader("X-CSRF-TOKEN", $('meta[name="csrf-token"]').attr('content'));
            },
            error: function (xhr) {
                sy.responseHandle(xhr);
                error && error.call(this, {
                    success: false
                }, xhr);
            }
        });
    };
});

$(function () {

    var setEditData = function (sign) {
        var gridEditor = $('.grid-editor:hidden');
        var gridIds = [];
        if (gridEditor.length) {
            gridEditor.each(function () {
                var gridId = $(this).data('grid');
                var grid = $('#' + gridId);
                var ids = grid.jqGrid('getDataIDs');
                var gridDatas;
                var editable = false;

                $.each(ids, function (key, rowid) {
                    var ind = grid.jqGrid('getInd', rowid, true);
                    if ($(ind).attr('editable') === '1') {
                        grid.jqGrid('saveRow', rowid);
                        if (editable === false) {
                            editable = true;
                        }
                    }
                });

                if (editable === true) {
                    gridIds.push(gridId);
                }
                // clearseach();
                $.isFunction(grid.get(0).clearToolbar) &&
                    grid.get(0).clearToolbar(true);
                gridDatas = grid.jqGrid('getEditRowData');
                // 返回json字符串
                $(this).val(JSON ? JSON.stringify(gridDatas) : '[]');
            });
        }
    }

    /**
 * ajax 提交表单,获取form 提交表单数据
 * @param options
 * @returns
 */
    $.fn.drsubmit = function () {
        var that = this;
        return that.off('ajaxdata').on('ajaxdata', function (e, opts) {

            var
                form = that.closest('form'),
                lock = false,

                defaults = {
                    type: 'POST',
                    dataType: 'json',
                    beforeSubmit: function () {
                        lock = true;
                    },
                    success: function (data) {
                        if (opts.close) {
                            opts.model.modal('hide');
                        }
                        opts.toolbar.reloadGrid(true);
                        sy.tip(data.message, data.success);
                    },
                    error: function (xhr, status, error, form) {
                        sy.responseHandle(xhr);
                    },
                    complete: function () {
                        sy.unmask();
                        sy.thread(function () {
                            lock = false;
                        }, 500);
                    }
                };
            setEditData();
            opts = $.extend({}, defaults, opts);
            lock || form.ajaxSubmit(opts);
        });
    };

    var dosubmit = $('#dosubmit');
    var actionForm = $('#actionForm');
    if (dosubmit.length > 0 && actionForm.length > 0) {
        dosubmit.drsubmit();
    }
})
